package com.ybwh.springboot2.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.google.common.collect.Lists;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @author fanbeibei
 * @version 1.2.0
 * @date 2021/12/23 22:19
 */
public class EasyExcelUtil {


    public static void export(List records, Class recordClass, String fileName, String sheetName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (CollectionUtils.isEmpty((Collection) records)) {
            records = Lists.newArrayList();
        }

        response.setContentType("application/x-download");
        response.setCharacterEncoding("utf-8");
        String newFileName = new String((fileName + (new SimpleDateFormat("yyyy-MM-dd")).format(new Date())).getBytes(), "UTF-8") + ".xlsx";
        response.addHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(newFileName, "UTF-8") + "\"");
        EasyExcel.write(response.getOutputStream(), recordClass).sheet(sheetName).doWrite((List) records);
    }


    public static void export(List records, Class recordClass, String fileName, String sheetName, HttpServletRequest request, HttpServletResponse response, List<String> includeColumnFiledNames) throws IOException {
        if (CollectionUtils.isEmpty((Collection) records)) {
            records = Lists.newArrayList();
        }

        response.setContentType("application/x-download");
        response.setCharacterEncoding("utf-8");
        String newFileName = new String((fileName + (new SimpleDateFormat("yyyy-MM-dd")).format(new Date())).getBytes(), "UTF-8") + ".xlsx";
        response.addHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(newFileName, "UTF-8") + "\"");
        ((ExcelWriterSheetBuilder) EasyExcel.write(response.getOutputStream(), recordClass).sheet(sheetName).includeColumnFiledNames(includeColumnFiledNames)).doWrite((List) records);
    }


}
